//
//  SoundHandler.m
//  
//
//  Created by Fred Havemeyer on 12/30/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "__SoundHandler.h"


@implementation SoundHandler
- (id)init
{
	if ((self = [super init]) != nil)
	{
		somethingPlaying = NO;
		
		idle = swinging = striking = hitting = NO;
		
		baseSoundFolderPath = @"";
		
		[self setDelegate:self];
		[self setVibrationEnabled:YES];
	}
	return self;
}
- (void)dealloc
{
	//[err release];
	[currentSound release];
	[previousSound release];
	[nextSound release];
	[super dealloc];
}
- (void)playSoundWithFile:(NSString *)file ofType:(int)type
{
	NSLog(file);
	currentSound = [[NSString stringWithString:baseSoundFolderPath] stringByAppendingString:file];
	NSLog(baseSoundFolderPath);
	
	// Begin playing hierarchy.
	/*
		Idle will play if and only if swinging, striking, and hitting are all NO
		swinging will play if and only if strikign and hitting are all NO
		striking will play if and only if hitting is NO
		hitting will play immedietly
		
		All sounds of the same type will have the currently playing sound take precidence.
	*/
	switch (type)
	{
		case IDLE:
			if ((somethingPlaying && idle) || swinging || striking || hitting)
				return;
			idle = YES;
			swinging = striking = hitting = NO;
			break;
		case SWING:
			if ((somethingPlaying && swinging) || striking || hitting)
				return;
			swinging = YES;
			idle = striking = hitting = NO;
			break;
		case STRIKE:
			if ((somethingPlaying && striking) || hitting)
				return;
			striking = YES;
			idle = swinging = hitting = NO;
			break;
		case HIT:
			if (somethingPlaying && hitting)
				return;
			hitting = YES;
			idle = swinging = striking = NO;
			break;
	}
	
	// The sound has passed the gauntlet, lets play it!
	soundFile = [[AVItem alloc] initWithPath:currentSound error:&err];
	if (err != nil)
		NSLog(@"Sound loading error!");
	NSLog(@"Playing sound!");
	[self setCurrentItem:soundFile];
	[self setCurrentTime:(double)0.0];
	[self play:&err];
	somethingPlaying = YES;
}
- (void)itemFinishedPlaying:(id)fp8
{
	somethingPlaying = NO;
	NSLog(@"Something finished playing!");
	[soundFile release];
	
	// If the saber was turning on, set turning on to off.
	if (turningOn)
		*turningOn = NO;
	
	previousSound = currentSound;
	currentSound = @"";
	idle = swinging = hitting = striking = NO;
}
- (void)loadSoundsInFolder()
{
	//NSLog(baseSoundFolderPath);
	//currentSound = [[NSString stringWithString:baseSoundFolderPath] stringByAppendingString:file];
	
}
- (void)playSoundTurningOn:(NSString *)file b:(BOOL *)b
{
	turningOn = b;
	[self playSoundWithFile:file ofType:TURN_ON];
}
- (void)setNextSound:(NSString *)file
{
	nextSound = file;
}
- (void)killCurrentSound
{	
	
}
- (void)setBaseFilePath:(NSString *)path
{
	//NSLog(path);
	baseSoundFolderPath = [path retain];
}
@end
